<template>
  <el-container class="order-container">
    <!-- 顶部导航 -->
    <el-header class="header">
      <div class="logo">
        <el-icon class="logo-icon"><Menu /></el-icon>
        <span class="logo-text">动态字段管理系统</span>
      </div>
      <div class="user-info">
        <el-avatar icon="User" size="small"></el-avatar>
        <span class="user-name">管理员</span>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <el-container>
      <!-- 侧边菜单 -->
      <el-aside width="200px" class="aside">
        <el-menu
          default-active="3"
          class="menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="1">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="2">
            <el-icon><User /></el-icon>
            <span>客户管理</span>
          </el-menu-item>
          <el-menu-item index="3">
            <el-icon><ShoppingCart /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          <el-menu-item index="4">
            <el-icon><Setting /></el-icon>
            <span>字段配置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 订单管理内容 -->
      <el-main class="main-content">
        <el-card class="content-card">
          <div slot="header" class="card-header">
            <span>订单管理</span>
            <el-button type="primary" icon="Plus" @click="openAddDialog">新增订单</el-button>
          </div>

          <!-- 动态查询表单 -->
          <dynamic-query-form 
            :fields="safeQueryFields"
            @query="handleQuery"
            @reset="handleReset"
          ></dynamic-query-form>

          <!-- 订单数据表格 -->
          <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%;"
            size="small"
            v-loading="loading"
          >
            <!-- 序号列 -->
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
            ></el-table-column>

            <!-- 动态字段列 -->
            <el-table-column
              v-for="field in safeTableFields"
              :key="field.fieldName"
              :label="field.displayName"
              :align="field.fieldType === 'number' ? 'right' : 'left'"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <!-- 固定字段 -->
                <template v-if="field.isBaseField">
                  <template v-if="field.formComponentType === 'select' && field.options">
                    {{ getOptionLabel(field.options.options, scope.row[field.fieldName]) }}
                  </template>
                  <template v-else-if="field.fieldType === 'date'">
                    {{ formatDate(scope.row[field.fieldName]) }}
                  </template>
                  <template v-else-if="field.fieldName === 'amount'">
                    {{ formatCurrency(scope.row[field.fieldName]) }}
                  </template>
                  <template v-else-if="field.fieldType === 'number'">
                    {{ formatNumber(scope.row[field.fieldName]) }}
                  </template>
                  <template v-else>
                    {{ scope.row[field.fieldName] || '-' }}
                  </template>
                </template>

                <!-- 扩展字段 -->
                <template v-else>
                  <template v-if="scope.row.extFields?.[field.systemFieldName] != null">
                    <template v-if="field.formComponentType === 'select' && field.options">
                      {{ getOptionLabel(field.options.options, scope.row.extFields[field.systemFieldName]) }}
                    </template>
                    <template v-else-if="field.fieldType === 'boolean'">
                      {{ scope.row.extFields[field.systemFieldName] ? '是' : '否' }}
                    </template>
                    <template v-else-if="field.fieldType === 'date'">
                      {{ formatDate(scope.row.extFields[field.systemFieldName]) }}
                    </template>
                    <template v-else-if="field.fieldName === 'discount'">
                      {{ formatNumber(scope.row.extFields[field.systemFieldName], 2) }}%
                    </template>
                    <template v-else-if="field.fieldType === 'number'">
                      {{ formatNumber(scope.row.extFields[field.systemFieldName]) }}
                    </template>
                    <template v-else>
                      {{ scope.row.extFields[field.systemFieldName] || '-' }}
                    </template>
                  </template>
                  <template v-else>-</template>
                </template>
              </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column
              label="操作"
              width="120"
              align="center"
            >
              <template #default="scope">
                <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" danger @click="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 16px; text-align: right;"
          ></el-pagination>
        </el-card>
      </el-main>
    </el-container>
  </el-container>

  <!-- 新增/编辑弹窗 -->
  <el-dialog 
    :title="dialogTitle" 
    v-model="dialogVisible"
    width="70%"
    destroy-on-close
  >
    <dynamic-form 
      :fields="safeAllFields"
      :initial-data="formData"
      :module-id="moduleId"
      @submit="handleFormSubmit"
      @cancel="dialogVisible = false"
    ></dynamic-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
// 导入组件和工具
import DynamicQueryForm from '../components/DynamicQueryForm.vue'
import DynamicForm from '../components/DynamicForm.vue'
import { formatDate, formatCurrency, formatNumber, getOptionLabel } from '../utils/format'
// 导入API
import { getFieldsByModuleId } from '../api/field'
import { queryOrder, getOrder, saveOrder, deleteOrder } from '../api/order'
// 导入图标
import { House, User, ShoppingCart, Setting, Menu, Plus } from '@element-plus/icons-vue'

const router = useRouter()
const moduleId = 2 // 订单管理模块ID固定为2

// 页面状态
const loading = ref(false)
const allFields = ref([]) // 所有字段（固定+扩展）
const tableData = ref([]) // 表格数据
const pageNum = ref(1) // 当前页码
const pageSize = ref(10) // 每页条数
const total = ref(0) // 总条数

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增订单')
const formData = ref({}) // 表单数据

// 安全处理 - 确保allFields始终是数组
const safeAllFields = computed(() => {
  if (!Array.isArray(allFields.value)) {
    console.warn('allFields 不是一个数组，已自动转换为空数组')
    return []
  }
  return allFields.value
})

// 安全的查询字段和表格字段
const safeQueryFields = computed(() => {
  return safeAllFields.value.filter(field => field.isQueryable)
})

const safeTableFields = computed(() => {
  return safeAllFields.value.filter(field => field.isTableDisplay)
})

// 菜单选择事件
const handleMenuSelect = (index) => {
  switch (index) {
    case '1':
      router.push('/')
      break
    case '2':
      router.push('/customer')
      break
    case '3':
      router.push('/order')
      break
    case '4':
      router.push('/field-config')
      break
    default:
      break
  }
}

// 初始化页面
const init = async () => {
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  try {
    // 获取字段定义
    const fieldsRes = await getFieldsByModuleId(moduleId)
    // 确保返回的是数组
    allFields.value = Array.isArray(fieldsRes.data?.data) 
      ? fieldsRes.data.data 
      : (Array.isArray(fieldsRes.data) ? fieldsRes.data : [])
    
    console.log('订单模块字段数据:', allFields.value)
    
    // 初始查询
    await handleQuery([])
  } catch (error) {
    ElMessage.error('初始化失败：' + (error.response?.data?.message || error.message))
    console.error('初始化错误:', error)
    allFields.value = []
  } finally {
    loadingInstance.close()
  }
}

// 处理查询
const handleQuery = async (params) => {
  loading.value = true
  try {
    const res = await queryOrder(moduleId, params, pageNum.value, pageSize.value)
    const responseData = res.data?.data || res.data || {}
    
    tableData.value = Array.isArray(responseData.records) ? responseData.records : []
    total.value = Number(responseData.total) || 0
    
    console.log('订单查询结果:', tableData.value)
  } catch (error) {
    ElMessage.error('查询失败：' + (error.response?.data?.message || error.message))
    console.error('查询错误:', error)
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 重置查询
const handleReset = () => {
  pageNum.value = 1
  handleQuery([])
}

// 打开新增弹窗
const openAddDialog = () => {
  dialogTitle.value = '新增订单'
  formData.value = { 
    moduleId,
    extFields: {}
  }
  dialogVisible.value = true
}

// 打开编辑弹窗
const handleEdit = async (row) => {
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  try {
    const res = await getOrder(row.id)
    const order = res.data?.data || res.data || {}
    
    // 处理扩展字段
    const extFields = {}
    safeAllFields.value.forEach(field => {
      if (!field.isBaseField && order.extFields?.[field.systemFieldName] != null) {
        extFields[field.fieldName] = order.extFields[field.systemFieldName]
      }
    })
    
    formData.value = { ...order, extFields }
    dialogTitle.value = '编辑订单'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载失败：' + (error.response?.data?.message || error.message))
    console.error('加载详情错误:', error)
  } finally {
    loadingInstance.close()
  }
}

// 处理删除
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '确定要删除这条订单数据吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteOrder(id)
      ElMessage.success('删除成功')
      handleQuery([])
    } catch (error) {
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message))
      console.error('删除错误:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 处理表单提交
const handleFormSubmit = async (data) => {
  const loadingInstance = ElLoading.service({ text: '保存中...' })
  try {
    // 处理扩展字段
    const extFields = {}
    safeAllFields.value.forEach(field => {
      if (!field.isBaseField && data.extFields?.[field.fieldName] != null) {
        extFields[field.systemFieldName] = data.extFields[field.fieldName]
      }
    })
    
    const submitData = { ...data, extFields }
    await saveOrder(submitData)
    
    ElMessage.success(data.id ? '编辑成功' : '新增成功')
    dialogVisible.value = false
    handleQuery([])
  } catch (error) {
    ElMessage.error('保存失败：' + (error.response?.data?.message || error.message))
    console.error('保存错误:', error)
  } finally {
    loadingInstance.close()
  }
}

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size
  pageNum.value = 1
  handleQuery([])
}

const handleCurrentChange = (page) => {
  pageNum.value = page
  handleQuery([])
}

// 调试：监听数据变化
watch([allFields, tableData], ([newFields, newTableData]) => {
  console.log('字段数据变化:', newFields)
  console.log('表格数据变化:', newTableData)
}, { deep: true })

// 组件挂载时初始化
onMounted(() => {
  init()
})
</script>

<style scoped>
.order-container { 
  height: 100vh; 
  display: flex; 
  flex-direction: column; 
}

/* 顶部导航 */
.header {
  background: #165DFF;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
}
.logo { 
  display: flex; 
  align-items: center; 
}
.logo-icon { 
  font-size: 24px; 
  margin-right: 8px; 
}
.logo-text { 
  font-size: 18px; 
  font-weight: 500; 
}
.user-info { 
  display: flex; 
  align-items: center; 
}
.user-name { 
  margin-left: 8px; 
  font-size: 14px; 
}

/* 侧边菜单 */
.aside { 
  background: #f5f7fa; 
  border-right: 1px solid #e4e7ed; 
}
.menu { 
  border-right: none; 
}

/* 主内容 */
.main-content { 
  background: #f5f7fa; 
  padding: 24px; 
  overflow-y: auto; 
}
.content-card { 
  height: calc(100% - 24px); 
  display: flex; 
  flex-direction: column; 
}
.card-header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
}
</style>
